﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;

namespace TorchView.PakViewer.Zip
{
    public class ZipTree
    {
        public BaseZipNode Root { get; private set; }

        public ZipTree(){
            Root = new DirectoryNode("media/","media");
        }

        public bool Add(ZipEntry entry)
        {
            string filename = entry.FileName;
            if(filename.Equals("media/")){
                return true;
            }
            else
            {
                string[] paths = filename.Split('/');
            
                return Add(Root, entry, paths, 1);
            }
        }

        private bool Add(BaseZipNode parent, ZipEntry entry, string[] paths, int depth)
        {
            //If directory entry, last element in paths[] is empty
            if (entry.IsDirectory && depth == paths.Length - 2)
            {
                IZipNode node = parent.FindChild(paths[depth]);
                if (node == null)
                {
                    node = new DirectoryNode(entry.FileName, paths[depth]);
                    parent.AddChild(node);
                }
                return true;
            }
            else if (depth == paths.Length - 1)
            {
                ZipNode node = new ZipNode(entry, paths[depth]);
                parent.AddChild(node);
                return true;
            }
            else if (depth < paths.Length)
            {
                BaseZipNode newParent = (BaseZipNode)parent.FindChild(paths[depth]);
                if (newParent == null)
                {
                    //Add missing directory
                    StringBuilder filename = new StringBuilder();
                    for (int i = 0; i <= depth; ++i)
                    {
                        filename.Append(paths[i]);
                        filename.Append('/');
                    }

                    newParent = new DirectoryNode(filename.ToString(), paths[depth]);
                    parent.AddChild(newParent);
                }
                return Add(newParent, entry, paths, depth + 1);
            }
            return false;
        }

        
    }
}
